<template>
  <div class="chart-wrapper">
    <h2>实时温度折线图</h2>
    <!-- vue-echarts 组件 -->
    <v-chart
        ref="chart"
        :option="chartOption"
        autoresize
        style="height: 300px; width: 100%"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import axios from 'axios'
import 'echarts'
import { use } from 'echarts/core'
import { LineChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent
} from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'
import VChart from 'vue-echarts'
import {getTemperature} from "@/api/equipment-service/machine.js";

// 注册 ECharts 组件
use([
  LineChart,
  GridComponent,
  TooltipComponent,
  TitleComponent,
  LegendComponent,
  CanvasRenderer
])

/* 图表配置 */
const chartOption = reactive({
  title: { text: '温度趋势 (最近 20 秒)', left: 'center' },
  tooltip: {
    trigger: 'axis',
    formatter: '{b}<br/>{a}: {c} °C'
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: []
  },
  yAxis: {
    type: 'value',
    name: '温度 °C',
    min: data => Math.floor(data.min - 1),
    max: data => Math.ceil(data.max + 1)
  },
  series: [{
    name: '温度',
    type: 'line',
    data: [],
    smooth: true,
    symbol: 'none',
    lineStyle: { color: '#409EFF', width: 2 },
    areaStyle: { color: 'rgba(64,158,255,.2)' }
  }]
})

/* 拉取数据并刷新图表 */
let timer = null
async function fetchData () {
  try {
    const response = await getTemperature()
    console.log(response)
    const x = response.map(d => new Date(d.numberDate).toLocaleTimeString())
    const y = response.map(d => d.temperature)
    chartOption.xAxis.data = x
    chartOption.series[0].data = y
  } catch (e) {
    console.error('拉取温度数据失败', e)
  }
}

onMounted(() => {
  fetchData()
  timer = setInterval(fetchData, 18_000)
})

onBeforeUnmount(() => {
  timer && clearInterval(timer)
})
</script>

<style scoped>
.chart-wrapper {
  max-width: 800px;
  margin: 40px auto;
}
</style>